package org.ssi.web.struts.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateConverter implements Converter {
	private static final Log log = LogFactory.getLog(DateConverter.class);

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	public DateConverter(String formatPattern) {
		if (StringUtils.isNotBlank(formatPattern)) {
			format = new SimpleDateFormat(formatPattern);
		}
	}

	public Object convert(Class arg0, Object value) {
		if (log.isDebugEnabled()) {
			log.debug("Class arg0:" + arg0);
			log.debug("Object value:" + value);
		}
		if (value instanceof Date) {
			if (log.isInfoEnabled()) {
				log.info("value is instanceof Date, return value:" + value);
			}
			return value;
		}
		try {
			
			String dateStr = (String) value;
			if (StringUtils.isNotBlank(dateStr)) {
				return format.parse(dateStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return null;
	}
	
	public static void main(String[] args) throws ParseException{
		DateConverter d = new DateConverter("yyyy-MM-dd hh:mm:ss");
		System.out.println(d.format.parse("2012-12-01 10:10:10"));
	}
}